package main

import (
	"fmt"
	"strconv"
	"strings"
)

type Apper struct {
	First int
	Last  int
	Count int
}

func main() {
	list := []int{1, 2, 2, 3, 1}
	fmt.Println(findShortestSubArray(list))
}

// subdomainVisits 811. 子域名访问计数
// link https://leetcode.cn/problems/subdomain-visit-count/
func subdomainVisits(cpdomains []string) []string {
	hashMap := map[string]int{}
	for _, domainStr := range cpdomains {
		// 分拆字符串
		arr := strings.Split(domainStr, " ")
		if len(arr) != 2 {
			continue
		}
		count, _ := strconv.Atoi(arr[0])
		for {
			hashMap[arr[1]] += count
			// 获取字符串第一个点的位置
			index := strings.Index(arr[1], ".")
			if index == -1 { // 找不到.则跳出循环
				break
			}
			// 缩小字符串为当前字符串开始为起点
			arr[1] = arr[1][index+1:]
		}
	}

	var res []string
	for k, v := range hashMap {
		res = append(res, fmt.Sprintf("%d %s", v, k))
	}

	return res
}

// findShortestSubArray 697. 数组的度
// link https://leetcode.cn/problems/degree-of-an-array/submissions/
func findShortestSubArray(nums []int) int {

	hashMap := make(map[int]*Apper, len(nums))
	for k, v := range nums {
		if x, ok := hashMap[v]; ok {
			// 更新最后出现位置
			x.Last = k
			x.Count++
			hashMap[v] = x
		} else {
			hashMap[v] = &Apper{
				First: k,
				Count: 1,
				Last:  k,
			}
		}
	}

	var maxCount int
	var ans int
	for _, v := range hashMap {
		if maxCount < v.Count {
			maxCount, ans = v.Count, v.Last-v.First+1
		} else if maxCount == v.Count {
			ans = min(ans, v.Last-v.First+1)
		}
	}

	return ans
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}
